<template>
  <el-card>
    <!-- 标题 + 新增 -->
    <template #header>
      <div class="flex-between">
        <span>常数项目管理</span>
        <el-button type="primary" @click="openDialog">新增项目</el-button>
      </div>
    </template>

    <!-- 查询区 -->
    <el-form :inline="true" class="mb-3">
      <el-form-item label="类别">
        <el-select v-model="query.typeId" placeholder="全部" clearable style="width:180px">
          <el-option
              v-for="t in typeOptions"
              :key="t.id"
              :label="t.name"
              :value="t.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="query.keyword" placeholder="编码 / 名称" clearable />
      </el-form-item>
      <el-button type="primary" @click="onQuery">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form>

    <!-- 列表 -->
    <el-table :data="list" stripe border style="width: 100%">
      <el-table-column prop="typeId" label="类型ID" width="100" />
      <el-table-column prop="code" label="编码" width="120" />
      <el-table-column prop="name" label="名称" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="onEdit(row.id)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="onDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="mt-4"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="query.page"
        v-model:page-size="query.pageSize"
        @current-change="onPageChange"
        @size-change="onSizeChange"
    />

    <!-- 新增 / 编辑 对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="480px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
        <el-form-item label="类别" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择类别">
            <el-option
                v-for="t in typeOptions"
                :key="t.id"
                :label="t.name"
                :value="t.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'

// ---- 查询条件 & 分页 ----
const query = reactive({
  typeId: undefined as number | undefined,
  keyword: '',
  page: 1,
  pageSize: 10
})
const total = ref(0)

// ---- 数据列表 ----
interface Item {
  id: number
  typeId: number
  code: string
  name: string
}
const list = ref<Item[]>([])

// ---- 类型选项 ----
const typeOptions = ref<{ id: number; name: string }[]>([])
async function loadTypeOptions() {
  const res = await request.get('/api/master/constant/type/list')
  const raw: any[] = res.data
  typeOptions.value = raw.map(r => ({
    id:   r.id,
    name: r.constanttypename
  }))
}

// ---- 加载项目列表 ----
async function loadData() {
  const res = await request.get('/api/master/constant/item/list')
  const raw: any[] = res.data

  // 过滤
  const filtered = raw.filter(r => {
    const matchType = !query.typeId || r.constanttypeid === query.typeId
    const matchKeyword =
        !query.keyword ||
        r.constantcode.includes(query.keyword) ||
        r.constantname.includes(query.keyword)
    return matchType && matchKeyword
  })

  // 映射
  const mapped = filtered.map(r => ({
    id:     r.id,
    typeId: r.constanttypeid,
    code:   r.constantcode,
    name:   r.constantname
  }))

  total.value = mapped.length
  const start = (query.page - 1) * query.pageSize
  list.value = mapped.slice(start, start + query.pageSize)
}

function onQuery() {
  query.page = 1
  loadData()
}
function onReset() {
  query.typeId = undefined
  query.keyword = ''
  query.page = 1
  loadData()
}
function onPageChange() { loadData() }
function onSizeChange() { loadData() }

// ---- 表单 & 对话框 ----
const dialogVisible = ref(false)
const dialogTitle   = ref('')
const formRef       = ref()
const form = reactive<{ typeId: number; code: string; name: string }>({
  typeId: 0,
  code: '',
  name: ''
})
const rules = {
  typeId: [{ required: true, message: '请选择类别', trigger: 'change' }],
  code:   [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name:   [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
let editId = 0

function openDialog() {
  dialogTitle.value = '新增项目'
  form.typeId = 0
  form.code = ''
  form.name = ''
  editId = 0
  dialogVisible.value = true
}

async function onEdit(id: number) {
  const res = await request.get(`/api/master/constant/item/getById/${id}`)
  const data: any = res.data
  form.typeId = data.constanttypeid
  form.code   = data.constantcode
  form.name   = data.constantname
  editId = id
  dialogTitle.value = '编辑项目'
  dialogVisible.value = true
}

async function onDelete(id: number) {
  await ElMessageBox.confirm('确认删除这条记录吗？', '警告', { type: 'warning' })
  await request.delete(`/api/master/constant/item/deleteById/${id}`)
  ElMessage.success('删除成功')

  if (list.value.length === 1 && query.page > 1) {
    query.page--
  }
  loadData()
}

async function onSubmit() {
  await formRef.value.validate()
  const payload = {
    constanttypeid: form.typeId,
    constantcode:   form.code,
    constantname:   form.name,
    id: editId || undefined
  }
  await request.post('/api/master/constant/item/saveOrUpdate', payload)
  ElMessage.success('操作成功')
  dialogVisible.value = false
  loadData()
}

// ---- 生命周期 ----
onMounted(async () => {
  await loadTypeOptions()
  await loadData()
})
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb-3 {
  margin-bottom: 12px;
}
.mt-4 {
  margin-top: 12px;
}
</style>
